<?php
	error_reporting(0);
	include_once('./src/connect.php');

	if ($_POST['username'] && $_POST['password']) {
		$username = trim($_POST['username']);
		$password = trim($_POST['password']);

		$query = "SELECT uid,password FROM ark_user WHERE username='".$username."'";

		$result = mysql_query($query, $link);
		list($uid, $password_db) = mysql_fetch_array($result);

		if ($uid >= 1) {
			if (md5($password) == $password_db) {
				session_start();
				$_SESSION['username'] = $username;
				header("Location: index.php");
			}
			else {
				exit("Wrong Password");
			}
		}
		else {
			if ($username == $password) {
				$password_db = md5($password);
				$query = "INSERT INTO ark_user (username,password,university) VALUES ('$username', '$password_db', 1)";
				$result = mysql_query($query, $link);
				if (mysql_affected_rows() == 1) {
					session_start();
					$_SESSION['username'] = $username;
					$_SESSION['password'] = $password_db;
					header("Location: index.php");
				}
			}	
			else {
				header("Location: login.php");
			}
		}
	}

	require_once('./template/header.tpl.php');
?>

<form id="login" method="post" action="#"> 

    <h1>初始密码为学号</h1>
    
    <div>
    	<label for="username">学号</label> 
    	<input type="text" name="username" id="username" />
    </div>			

    <div>
    	<label for="password">密码</label>
    	<input type="password" name="password" id="password" />
    </div>			
    			
    <div class="submit">
        <button type="submit">登录</button>   
    </div> 
</form>	

<?php
	require_once('./template/footer.tpl.php');
?>
